using System;
using System.Web.UI;
using Tarantino.Samples.Core.Model;
using StructureMap;
using Tarantino.Core.Commons.Services.Repositories;

namespace Tarantino.Samples.UI
{
	public partial class EditSystemUser : Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			btn.Click += btn_OnClick;
		
			if (!Page.IsPostBack)
			{
				if (isExistingSystemUser())
				{
					SystemUser systemUser = getExistingSystemUser();

					txtFirstName.Text = systemUser.FirstName;
					txtLastName.Text = systemUser.LastName;
					txtEmailAddress.Text = systemUser.EmailAddress;
					txtEncryptedPassword.Text = systemUser.EncryptedPassword;
				}
			}
		}

		private void btn_OnClick(object sender, EventArgs e)
		{
			SystemUser systemUser = isExistingSystemUser() ? getExistingSystemUser() : new SystemUser();

			systemUser.FirstName = txtFirstName.Text;
			systemUser.LastName = txtLastName.Text;
			systemUser.EmailAddress = txtEmailAddress.Text;
			systemUser.EncryptedPassword = txtEncryptedPassword.Text;

			IPersistentObjectRepository repository = ObjectFactory.GetInstance<IPersistentObjectRepository>();
			repository.Save(systemUser);
			
			Response.Redirect("ViewSystemUsers.aspx");
		}

		private SystemUser getExistingSystemUser()
		{
			IPersistentObjectRepository repository = ObjectFactory.GetInstance<IPersistentObjectRepository>();
			return repository.GetById<SystemUser>(getId());
		}

		private Guid getId()
		{
			return new Guid(Request.Params["id"]);
		}

		private bool isExistingSystemUser()
		{
			bool isExisting = Request.Params["id"] != null;
			return isExisting;
		}
	}
}